import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';

class LoginLogic extends GetxController {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  final RxBool rememberMe = false.obs;
  final RxBool showPassword = false.obs;

  final RxString phone = "".obs;
  final RxString password = "".obs;
  final RxString phoneErrorText = "".obs;
  final RxString passwordErrorText = "".obs;

  late Box<String> settingsBox;

  @override
  void onInit() {
    super.onInit();
    settingsBox = Hive.box<String>('settings');
    loadUserDetails();
  }

  void saveUserDetails(String phone, String password) {
    settingsBox.put('remembered_phone', phone);
    settingsBox.put('remembered_password', password);
  }

  void loadUserDetails() {
    final rememberedPhone = settingsBox.get('remembered_phone') ?? '';
    final rememberedPassword = settingsBox.get('remembered_password') ?? '';

    phoneController.text = rememberedPhone;
    passwordController.text = rememberedPassword;

    rememberMe.value = rememberedPhone.isNotEmpty && rememberedPassword.isNotEmpty;
  }

  void clearSavedUserDetails() {
    settingsBox.delete('remembered_phone');
    settingsBox.delete('remembered_password');
  }

  void onPhoneChanged(String value) {
    if (value.length > 11) {
      phoneController.text = value.substring(0, 11);
      phoneController.selection = TextSelection.fromPosition(
        TextPosition(offset: phoneController.text.length),
      );
      return;
    }
    phone.value = value;
    phoneErrorText.value = "";
  }

  void onPasswordChanged(String value) {
    password.value = value;
    passwordErrorText.value = "";
  }

  bool _validatePhone(String phone) {
    if (phone.isEmpty) {
      phoneErrorText.value = "请输入手机号码";
      return false;
    }
    if (phone.length != 11 || !RegExp(r'^[0-9]{11}$').hasMatch(phone)) {
      phoneErrorText.value = "请输入正确的手机号码";
      return false;
    }
    return true;
  }

  bool _validatePassword(String password) {
    if (password.isEmpty) {
      passwordErrorText.value = "请输入密码";
      return false;
    }
    if (password.length < 6) {
      passwordErrorText.value = "密码长度不能少于6位";
      return false;
    }
    return true;
  }

  bool validateLogin() {
    final isPhoneValid = _validatePhone(phone.value);
    final isPasswordValid = _validatePassword(password.value);
    return isPhoneValid && isPasswordValid;
  }

  @override
  void onClose() {
    phoneController.dispose();
    passwordController.dispose();
    super.onClose();
  }
}